//
//  DQBAnswerViewController.m
//  DrivingQuestionBank
//
//  Created by mac on 2023/12/28.
//

#import "DQBAnswerViewController.h"
#import "DQBOptionCollectionViewCell.h"
#import "DQBQuestionCollectionViewCell.h"
#import "DQBQuestionModel.h"
#import <MJExtension.h>
#import "CustomBottomToolView.h"

@interface DQBAnswerViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>


@property (nonatomic ,strong) UICollectionView *answerCollectonView;
@property (nonatomic ,strong) NSIndexPath *indexPath;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) CustomBottomToolView *customBottomView;
@property (nonatomic, strong) UIButton *likeBtn;
@end

@implementation DQBAnswerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self answerSubView];
    [self setCustomBottomView];
    [self requestData];
    
    self.likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.likeBtn setTitle:@"收藏" forState:UIControlStateNormal];
    [self.likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.likeBtn addTarget:self action:@selector(touchlikeBtn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithCustomView:self.likeBtn];
    self.navigationItem.rightBarButtonItem = rightBar;
}

- (void)touchlikeBtn:(UIButton *)btn {
    self.likeBtn.selected = !btn;
    
}


- (void)setCustomBottomView {
    self.customBottomView = [[CustomBottomToolView alloc] initWithFrame:CGRectMake(20, ScreenHeight - SafeAreaBottomHeight - 64, ScreenWidth - 40, 64)];
    self.customBottomView.backgroundColor = [UIColor whiteColor];
    self.customBottomView.layer.cornerRadius = 32;
    self.customBottomView.layer.shadowOffset = CGSizeMake(1, 1);
    self.customBottomView.layer.shadowOpacity = 1;
    self.customBottomView.layer.shadowColor = DQBRGBHex(0x999999).CGColor;
    self.customBottomView.layer.shadowRadius = 5;
    
    @weakify(self);
    [self.customBottomView setClickPreviousBlock:^{
        if (weak_self.currentIndex == 0) {
            return;
        }
        weak_self.currentIndex --;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:weak_self.currentIndex];
        [weak_self.answerCollectonView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        
       
        weak_self.customBottomView.currentNum = [NSString stringWithFormat:@"%ld",(long)self.currentIndex + 1];
        
        //跳转到指定页
//        self.currentIndex = 0; // 要定位到的页面索引，比如第6页（索引从0开始）
//        CGFloat pageWidth = CGRectGetWidth(self.answerCollectonView.frame);
//        CGPoint offset = CGPointMake(ScreenWidth * self.currentIndex, 0);
//        [self.answerCollectonView setContentOffset:offset animated:NO];
        
    }];
    [self.customBottomView setClickNextBlock:^{
        if (weak_self.currentIndex == weak_self.dataSource.count - 1) {
            return;
        }
        weak_self.currentIndex ++;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:weak_self.currentIndex];
        [weak_self.answerCollectonView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
       
        weak_self.customBottomView.currentNum = [NSString stringWithFormat:@"%ld",(long)self.currentIndex + 1];
    }];
    [self.view addSubview:self.customBottomView];
}

- (void)requestData {
    if(_index == 0) {
        NSArray *originalArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"sequentialExercise"];
        _dataSource = [DQBQuestionModel mj_objectArrayWithKeyValuesArray:originalArr];
        
    } else if(_index == 1) {
        NSArray *originalArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"sequentialExercise"];
        _dataSource = [DQBQuestionModel mj_objectArrayWithKeyValuesArray:originalArr];
        
    } else if(_index == 1) {
        NSArray *originalArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"sequentialExercise"];
        _dataSource = [DQBQuestionModel mj_objectArrayWithKeyValuesArray:originalArr];
        
    } else if(_index == 1) {
        NSArray *originalArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"sequentialExercise"];
        _dataSource = [DQBQuestionModel mj_objectArrayWithKeyValuesArray:originalArr];
        
    } else if(_index == 1) {
        NSArray *originalArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"sequentialExercise"];
        _dataSource = [DQBQuestionModel mj_objectArrayWithKeyValuesArray:originalArr];
        
    } else {
        NSArray *originalArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"sequentialExercise"];
        _dataSource = [DQBQuestionModel mj_objectArrayWithKeyValuesArray:originalArr];
    }
    
    self.customBottomView.totalNum = [NSString stringWithFormat:@"%ld",_dataSource.count];
    self.customBottomView.currentNum = [NSString stringWithFormat:@"%ld",(long)self.currentIndex + 1];
    
    @weakify(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weak_self.answerCollectonView reloadData];
    });
}

- (void)answerSubView{
    [self.view addSubview:[self answerCollectonView]];
    
}

#pragma mark -- collectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return _dataSource.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    DQBQuestionModel *model = _dataSource[section];
    if (model.options.count == 2) {
        return 3;
    } else {
        return 5;
    }
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DQBQuestionModel *model = _dataSource[indexPath.section];
    if (indexPath.row == 0) {
        DQBQuestionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DQBQuestionCollectionViewCell" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    } else {
        DQBOptionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DQBOptionCollectionViewCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor grayColor];
        cell.optionLabel.text = model.options[indexPath.row - 1];
        cell.optionContentLabel.text = model.options[indexPath.row - 1];
        
        if(model.select.count > 0){
            if ([model.select isEqualToArray:model.answer]) {
                if([model.options[indexPath.row - 1] isEqualToString:model.select[0]]){
                    // 回答正确
                    cell.backgroundColor = [UIColor greenColor];
                }
            } else {
                // 回答错误
                if([model.options[indexPath.row - 1] isEqualToString:model.select[0]]){
                    // 回答正确
                    cell.backgroundColor = [UIColor redColor];
                }
                
                if([model.options[indexPath.row - 1] isEqualToString:model.answer[0]]){
                    // 回答正确
                    cell.backgroundColor = [UIColor greenColor];
                }
                
            }
        }
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DQBQuestionModel *model = _dataSource[indexPath.section];
    if (model.options.count == 2) {
        if(indexPath.row != 0){
            NSString *chooseStr = model.options[indexPath.row - 1];
           // NSMutableArray *selectedArr = [[NSMutableArray alloc] init];
            if (model.category == 0){
                [model.select removeAllObjects];
                [model.select addObject:chooseStr];
            } else {
                [model.select addObject:chooseStr];
            }
            
            [self.answerCollectonView reloadData];
        }
        
    } else {
        if(indexPath.row != 0){
            NSString *chooseStr = model.options[indexPath.row - 1];
           // NSMutableArray *selectedArr = [[NSMutableArray alloc] init];
            if (model.category == 0){
                [model.select removeAllObjects];
                [model.select addObject:chooseStr];
            } else {
                [model.select addObject:chooseStr];
            }
            
            [self.answerCollectonView reloadData];
        }
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //CGFloat pageWidth = CGRectGetWidth(self.answerCollectonView.frame);
    NSInteger currentPage = (NSInteger)(scrollView.contentOffset.x / ScreenWidth);
    self.currentIndex = currentPage;
    NSLog(@"当前页：%ld", (long)currentPage); // 加1是因为页码一般从1开始
    self.customBottomView.currentNum = [NSString stringWithFormat:@"%ld",(long)self.currentIndex + 1];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UICollectionViewLayoutAttributes *attributes = [self.answerCollectonView layoutAttributesForItemAtIndexPath:self.indexPath];
    self.answerCollectonView.contentOffset = CGPointMake(attributes.frame.origin.x, 0);
}
#pragma mark -- lazy
- (UICollectionView *)answerCollectonView{
    if (!_answerCollectonView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.estimatedItemSize = CGSizeMake(self.view.frame.size.width, 100);
        _answerCollectonView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
        _answerCollectonView.showsVerticalScrollIndicator = NO;
        _answerCollectonView.showsHorizontalScrollIndicator = NO;
        _answerCollectonView.delegate = self;
        _answerCollectonView.dataSource = self;
        [_answerCollectonView registerClass:[DQBQuestionCollectionViewCell class] forCellWithReuseIdentifier:@"DQBQuestionCollectionViewCell"];
        [_answerCollectonView registerClass:[DQBOptionCollectionViewCell class] forCellWithReuseIdentifier:@"DQBOptionCollectionViewCell"];
        _answerCollectonView.pagingEnabled = YES;
        _answerCollectonView.backgroundColor = [UIColor whiteColor];
    }
    return _answerCollectonView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
